package kokonut.admin;

import java.io.IOException;
import java.util.ArrayList;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import persistence.ProductPersistence;

import kokonut.shop.color.Color;
import kokonut.shop.product.Image;
import kokonut.shop.product.TShirtModel;
import kokonut.shop.size.Size;
import utils.ProductEditor;

public class SaveProductServlet extends HttpServlet {

    @Override
    public void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws IOException {
        String productName = req.getParameter("name");
        int ref = Integer.parseInt(req.getParameter("ref"));
        String type = req.getParameter("type");
        if (type.equals("T-Shirt")) {
            String[] sizes = req.getParameterValues("sizes");
            ArrayList<Size> availableSizes = ProductEditor.createSizes(sizes);
            availableSizes = ProductEditor.assignPriceToSizes(availableSizes, req);
            String[] colors = req.getParameterValues("colors");
            ArrayList<Color> availableColors = ProductEditor.createColors(colors);
            ArrayList<Image> images = ProductEditor.assignImages(req, availableColors);
            TShirtModel shirtModel = new TShirtModel(ref, productName, availableSizes, availableColors, images);
            //Se mira si ya existe un producto con esa referencia
            if (ProductEditor.unusedReference(shirtModel.getRef())) {
                ProductPersistence persistence = new ProductPersistence();
                persistence.saveModel(shirtModel);
                persistence.closePM();
            } else {
            	resp.setContentType("text/plain");
                resp.getWriter().println("La referencia ya esta siendo utilizada, el producto no se ha guardado");
                try {
					Thread.sleep(4);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
            }
        }
        resp.sendRedirect("/admin/shopAdmin");
    }
}